import { fetchRuleSet } from '@/api/manage'

import {deserialize, findFirstChildNode, resetItemPosition, resetParentPosition} from "@/lib/node-utils"
import Node from '@/lib/node'
import * as NodeType from '@/lib/node-type'
import Tree from "@/lib/tree";

const manage = {
    actions: {
        async FetchRuleSet({commit}, ruleSetCode) {
            let response = await fetchRuleSet({ruleSetCode})
            let { code, message, data } = response.data
            if (code !== 0) {
                throw new Error(message)
            }

            let root = new Node(NodeType.VARIABLE)
            deserialize(data, root)

            let nodes = root.nodes()
            // 赋值 ID 和宽度，宽度设为0是因为渲染的时候可以重新计算宽度
            nodes.forEach((node, index) => {
                node.meta.id = index
                node.meta.width = 0
            })

            let tree = new Tree()
            tree._root = root

            commit('SET_TREE', tree)
            commit('SET_CURRENT_NODE', root)
        }
    }
}

export default manage